package com.ruoyi.ichen.rabbitmq.common;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author ichen
 * @version V1.0
 * @ClassName: RabbitMQUtils
 * @Description: RabbitMQUtils
 * @Date 2020/7/26 14:30
 */
public class RabbitMQUtils {

    private static ConnectionFactory connectionFactory;

    static {
        //创建连接工厂,加载一次
        connectionFactory = new ConnectionFactory();
        //设置连接主机
        connectionFactory.setHost("119.23.138.111");
        //设置端口
        connectionFactory.setPort(5672);
        //设置连接虚拟主机
        connectionFactory.setVirtualHost("/ems");
        //设置访问虚拟主机的用户名和密码
        connectionFactory.setUsername("ichen");
        connectionFactory.setPassword("ichen123");
    }

    /**
     * 连接rabbitmq
     * @return
     */
    public static Connection getConnection() {
        try {
            //获取连接对象
            return connectionFactory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭连接和通道
     * @param channel
     * @param connection
     */
    public static void closeConnectionAndChannel(Channel channel,Connection connection){
        try {
            if (channel != null) channel.close();
            if (connection != null) connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
